<template>
  <h3>reactive函数的演示</h3>
  <hr>
  <div>员工的具体信息如下:</div>
  <div class="indent">姓名: {{emp.name}}</div>
  <div class="indent">年龄: {{emp.age}}</div>
  <div class="indent">职位: {{emp.position}}</div>
  <button @click="chgEmp">修改员工信息</button>
  <br>
  <br>
  <table border="0" cellpadding="4" cellspacing="0">
    <tr>
      <th>订单号</th>
      <th>客户名称</th>
      <th>金额</th>
    </tr>
    <tr v-for="order in emp.orders" :key="order.orderNo">
      <td>{{order.orderNo}}</td>
      <td>{{order.customer}}</td>
      <td>{{order.amount}}</td>
    </tr>
  </table>
  <button @click="addOrder">增加订单</button>
  <button @click="updateOrder">修改订单</button>
  <br>
  <br>
  <div>其他信息:</div>
  <div class="indent">办公地址: {{emp.others.address}}</div>
  <div class="indent">分公司: {{emp.others.division}}</div>
  <ul class="indent">职称: 
    <li v-for="(title, index) in emp.others.titles" :key="index">{{title}}</li>
  </ul>
  <button @click="addTitle">增加职称</button>
  <button @click="updateTitle">修改职称</button>
  <hr>

  <div>注意:</div>
  <p>
    1. reactive函数只针对对象类型的数据,不能处理基本数据类型.<br>
    2. 因为reactive函数内部使用了proxy,使得它可以对数组成员的更新作出响应,这在Vue2中没有实现.<br>
  </p>
</template>

<script>
import { reactive, isReactive, isRef } from '@vue/reactivity'
import { getObjClass } from 'common/utils/getObjClass'

export default {
  name: 'ReactiveDemo',
  setup() {
    let emp = reactive({
      name: '元始人',
      age: 28,
      position: '市场部',
      orders: [
        {orderNo: 'SP/2022/0001', customer: 'Adv Tech Ltd.', amount: 82395.88},
        {orderNo: 'SU/2022/2001', customer: 'International search', amount: 634723}
      ],
      others: {
        address: '月球南天门8024号',
        division: '环月分公司',
        titles: ['物理学教授', '高级研究员', '国家级专家']
      }
    })

    function chgEmp() {
      emp.name += '@'
      emp.age++
      emp.position += '~'
      emp.others.address += '#'
      emp.others.division += '%'
    }

    let orderIdx = 1

    function addOrder() {
      let order = {}
      order.orderNo  = 'New/2022/XX' + orderIdx
      order.customer =　'Customer-' + orderIdx
      order.amount   = 10 * orderIdx
      emp.orders.push(order)
      orderIdx++
    }

    function updateOrder() {
      emp.orders.forEach(element => {
        element.amount += 5
      })
    }

    let titleIdx = 1

    function addTitle() {
      emp.others.titles.push('title-' + titleIdx++)
    }

    function updateTitle() {
      for(let i = 0; i < emp.others.titles.length; i++) {
        emp.others.titles[i] += '*'
      }
    }

    console.log('emp is ref?', isRef(emp), ', emp is reactive?', isReactive(emp))
    console.log('emp is ', getObjClass(emp), emp)

    return {emp, chgEmp, addOrder, updateOrder, addTitle, updateTitle}
  },
}
</script>

<style scoped>

h3 {
  text-align: center;
}

table {
  margin-bottom: 10px;
}

th, td {
  border: 1px solid #7be;
}

.indent {
  padding-left: 20px;
}

</style>